'use client';

import React, {useState, useMemo} from 'react';
import {motion, AnimatePresence} from 'framer-motion';
import {
    MagnifyingGlassIcon,
    FunnelIcon,
    CalendarIcon,
    ClockIcon,
    PhotoIcon,
    TrashIcon,
    PencilIcon,
    CheckIcon,
} from '@heroicons/react/24/outline';
import {useAppStore} from '@/store';
import {cn} from '@/utils';
import {formatCoinChange, formatRelativeDate, formatTime} from '@/utils';
import type {Activity} from '@/types';
import Card from '@/components/ui/Card';

interface EntryBoardProps {
    className?: string;
}

const EntryBoard: React.FC<EntryBoardProps> = ({className}) => {
    const {activities, deleteActivity, settings} = useAppStore();
    const [searchTerm, setSearchTerm] = useState('');
    const [filterType, setFilterType] = useState<string>('all');
    const [filterMood, setFilterMood] = useState<string>('all');
    const [sortBy, setSortBy] = useState<'timestamp' | 'coinChange' | 'title'>('timestamp');
    const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
    const [showFilters, setShowFilters] = useState(false);

    // 批量删除相关状态
    const [isSelectionMode, setIsSelectionMode] = useState(false);
    const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

    // 筛选和搜索逻辑
    const filteredActivities = useMemo(() => {
        return activities
            .filter(activity => {
                // 搜索过滤
                const matchesSearch = !searchTerm ||
                    activity.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    activity.content.toLowerCase().includes(searchTerm.toLowerCase());

                // 类型过滤
                const matchesType = filterType === 'all' || activity.activityType === filterType;

                // 情绪过滤
                const matchesMood = filterMood === 'all' || activity.mood === filterMood;

                return matchesSearch && matchesType && matchesMood;
            })
            .sort((a, b) => {
                let comparison = 0;

                switch (sortBy) {
                    case 'timestamp':
                        comparison = new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
                        break;
                    case 'coinChange':
                        comparison = a.coinChange - b.coinChange;
                        break;
                    case 'title':
                        comparison = a.title.localeCompare(b.title);
                        break;
                }

                return sortOrder === 'asc' ? comparison : -comparison;
            });
    }, [activities, searchTerm, filterType, filterMood, sortBy, sortOrder]);

    // 统计数据
    const stats = useMemo(() => {
        const total = filteredActivities.length;
        const totalCoins = filteredActivities.reduce((sum, activity) => sum + activity.coinChange, 0);
        const positiveCoins = filteredActivities
            .filter(activity => activity.coinChange > 0)
            .reduce((sum, activity) => sum + activity.coinChange, 0);
        const negativeCoins = filteredActivities
            .filter(activity => activity.coinChange < 0)
            .reduce((sum, activity) => sum + Math.abs(activity.coinChange), 0);

        return {total, totalCoins, positiveCoins, negativeCoins};
    }, [filteredActivities]);

    const handleDeleteActivity = (id: string) => {
        if (window.confirm('确定要删除这条记录吗？')) {
            deleteActivity(id);
        }
    };

    // 批量删除处理
    const handleToggleSelectionMode = () => {
        setIsSelectionMode(!isSelectionMode);
        setSelectedIds(new Set());
    };

    const handleSelectActivity = (id: string) => {
        setSelectedIds(prev => {
            const newSet = new Set(prev);
            if (newSet.has(id)) {
                newSet.delete(id);
            } else {
                newSet.add(id);
            }
            return newSet;
        });
    };

    const handleSelectAll = () => {
        if (selectedIds.size === filteredActivities.length) {
            setSelectedIds(new Set());
        } else {
            setSelectedIds(new Set(filteredActivities.map(a => a.id)));
        }
    };

    const handleBatchDelete = () => {
        if (selectedIds.size === 0) return;

        if (window.confirm(`确定要删除选中的 ${selectedIds.size} 条记录吗？`)) {
            selectedIds.forEach(id => deleteActivity(id));
            setSelectedIds(new Set());
            setIsSelectionMode(false);
        }
    };

    const ActivityCard: React.FC<{ activity: Activity }> = ({activity}) => {
        const activityType = settings.activityTypes.find(type => type.name === activity.activityType);
        const moodConfig = settings.moodConfigs.find(mood => mood.name === activity.mood);
        const coinChange = formatCoinChange(activity.coinChange);
        const isSelected = selectedIds.has(activity.id);

        return (
            <motion.div
                layout
                initial={{opacity: 0, scale: 0.9}}
                animate={{opacity: 1, scale: 1}}
                exit={{opacity: 0, scale: 0.9}}
                transition={{type: 'spring', stiffness: 300, damping: 30}}
            >
                <Card hover className={cn(
                    "p-4 space-y-3 group",
                    isSelectionMode && isSelected && "ring-2 ring-blue-500"
                )}>
                    {/* 头部信息 */}
                    <div className="flex items-start justify-between">
                        {/* 选择模式下的复选框 */}
                        {isSelectionMode && (
                            <div className="mr-3">
                                <motion.button
                                    whileTap={{scale: 0.95}}
                                    onClick={() => handleSelectActivity(activity.id)}
                                    className={cn(
                                        "w-5 h-5 rounded border-2 flex items-center justify-center",
                                        isSelected
                                            ? "bg-blue-500 border-blue-500"
                                            : "border-gray-300 hover:border-gray-400"
                                    )}
                                >
                                    {isSelected && <CheckIcon className="w-3 h-3 text-white"/>}
                                </motion.button>
                            </div>
                        )}

                        <div className="flex items-center gap-3 flex-1">
                            <div className="flex items-center gap-2">
                                <span className="text-lg">{activityType?.icon || '📝'}</span>
                                <div>
                                    <h3 className="font-semibold text-gray-900">{activity.title}</h3>
                                    <div className="flex items-center gap-2 text-sm text-gray-500">
                                        <span>{moodConfig?.emoji}</span>
                                        <span>{activity.mood}</span>
                                    </div>
                                </div>
                            </div>

                            <div className={cn('text-sm font-semibold px-2 py-1 rounded-lg', coinChange.color)}>
                                {coinChange.sign}{coinChange.text}
                            </div>
                        </div>

                        {/* 操作按钮 */}
                        {!isSelectionMode && (
                            <div
                                className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                <motion.button
                                    whileHover={{scale: 1.1}}
                                    whileTap={{scale: 0.9}}
                                    className="p-1 text-gray-400 hover:text-blue-600 rounded"
                                    title="编辑"
                                >
                                    <PencilIcon className="w-4 h-4"/>
                                </motion.button>
                                <motion.button
                                    whileHover={{scale: 1.1}}
                                    whileTap={{scale: 0.9}}
                                    onClick={() => handleDeleteActivity(activity.id)}
                                    className="p-1 text-gray-400 hover:text-red-600 rounded"
                                    title="删除"
                                >
                                    <TrashIcon className="w-4 h-4"/>
                                </motion.button>
                            </div>
                        )}
                    </div>

                    {/* 内容 */}
                    {activity.content && (
                        <p className="text-gray-700 text-sm leading-relaxed">{activity.content}</p>
                    )}

                    {/* 图片 */}
                    {activity.images && activity.images.length > 0 && (
                        <div className="grid grid-cols-3 gap-2">
                            {activity.images.slice(0, 3).map((image, idx) => (
                                <motion.div
                                    key={idx}
                                    whileHover={{scale: 1.05}}
                                    className="aspect-square rounded-lg overflow-hidden cursor-pointer"
                                >
                                    <img
                                        src={image}
                                        alt={`Activity image ${idx + 1}`}
                                        className="w-full h-full object-cover"
                                    />
                                </motion.div>
                            ))}
                            {activity.images.length > 3 && (
                                <div
                                    className="aspect-square rounded-lg bg-gray-100 flex items-center justify-center text-gray-500 text-xs">
                                    +{activity.images.length - 3}
                                </div>
                            )}
                        </div>
                    )}

                    {/* 时间信息 */}
                    <div
                        className="flex items-center justify-between text-xs text-gray-500 pt-2 border-t border-gray-100">
                        <div className="flex items-center gap-1">
                            <CalendarIcon className="w-3 h-3"/>
                            <span>{formatRelativeDate(activity.timestamp)}</span>
                        </div>
                        <div className="flex items-center gap-1">
                            <ClockIcon className="w-3 h-3"/>
                            <span>{formatTime(activity.timestamp)}</span>
                        </div>
                    </div>
                </Card>
            </motion.div>
        );
    };

    return (
        <div className={cn('space-y-6', className)}>
            {/* 页面标题和统计 */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900">事项看板</h1>
                    <p className="text-gray-600 mt-1">管理和查看你的所有活动记录</p>
                </div>

                {/* 统计卡片和批量操作按钮 */}
                <div className="flex items-center gap-4">
                    <div className="flex gap-4">
                        <div className="text-center">
                            <div className="text-lg font-semibold text-gray-900">{stats.total}</div>
                            <div className="text-xs text-gray-500">总记录</div>
                        </div>
                        <div className="text-center">
                            <div className={cn(
                                'text-lg font-semibold',
                                stats.totalCoins >= 0 ? 'text-green-600' : 'text-red-600'
                            )}>
                                {stats.totalCoins >= 0 ? '+' : ''}{stats.totalCoins}
                            </div>
                            <div className="text-xs text-gray-500">净金币</div>
                        </div>
                    </div>

                    {/* 批量操作按钮 */}
                    {filteredActivities.length > 0 && (
                        <motion.button
                            whileHover={{scale: 1.05}}
                            whileTap={{scale: 0.95}}
                            onClick={handleToggleSelectionMode}
                            className={cn(
                                'px-4 py-2 rounded-lg border font-medium transition-colors',
                                isSelectionMode
                                    ? 'bg-blue-50 border-blue-500 text-blue-700'
                                    : 'border-gray-300 hover:border-gray-400 text-gray-700'
                            )}
                        >
                            {isSelectionMode ? '取消选择' : '批量管理'}
                        </motion.button>
                    )}
                </div>
            </div>

            {/* 搜索和筛选 */}
            <Card className="p-4 space-y-4">
                {/* 批量操作工具栏 */}
                {isSelectionMode && (
                    <div className="flex items-center justify-between pb-4 border-b border-gray-200">
                        <div className="flex items-center gap-3">
                            <button
                                onClick={handleSelectAll}
                                className="text-sm text-blue-600 hover:text-blue-700"
                            >
                                {selectedIds.size === filteredActivities.length ? '取消全选' : '全选'}
                            </button>
                            <span className="text-sm text-gray-500">
                已选择 {selectedIds.size} 条记录
              </span>
                        </div>

                        {selectedIds.size > 0 && (
                            <motion.button
                                whileHover={{scale: 1.05}}
                                whileTap={{scale: 0.95}}
                                onClick={handleBatchDelete}
                                className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 flex items-center gap-2"
                            >
                                <TrashIcon className="w-4 h-4"/>
                                删除选中
                            </motion.button>
                        )}
                    </div>
                )}

                {/* 搜索框和筛选按钮 */}
                <div className="flex gap-3">
                    <div className="relative flex-1">
                        <MagnifyingGlassIcon
                            className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400"/>
                        <input
                            type="text"
                            placeholder="搜索事项标题或内容..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        />
                    </div>
                    <motion.button
                        whileHover={{scale: 1.05}}
                        whileTap={{scale: 0.95}}
                        onClick={() => setShowFilters(!showFilters)}
                        className={cn(
                            'px-4 py-2 border rounded-lg flex items-center gap-2 transition-colors',
                            showFilters
                                ? 'border-blue-500 bg-blue-50 text-blue-700'
                                : 'border-gray-300 hover:border-gray-400'
                        )}
                    >
                        <FunnelIcon className="w-4 h-4"/>
                        筛选
                    </motion.button>
                </div>

                {/* 筛选控件 */}
                <AnimatePresence>
                    {showFilters && (
                        <motion.div
                            initial={{opacity: 0, height: 0}}
                            animate={{opacity: 1, height: 'auto'}}
                            exit={{opacity: 0, height: 0}}
                            className="grid grid-cols-1 md:grid-cols-4 gap-3 pt-4 border-t border-gray-200"
                        >
                            {/* 事项类型筛选 */}
                            <select
                                value={filterType}
                                onChange={(e) => setFilterType(e.target.value)}
                                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
                            >
                                <option value="all">所有类型</option>
                                {settings.activityTypes.map(type => (
                                    <option key={type.id} value={type.name}>{type.name}</option>
                                ))}
                            </select>

                            {/* 情绪筛选 */}
                            <select
                                value={filterMood}
                                onChange={(e) => setFilterMood(e.target.value)}
                                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
                            >
                                <option value="all">所有情绪</option>
                                {settings.moodConfigs.map(mood => (
                                    <option key={mood.id} value={mood.name}>{mood.emoji} {mood.name}</option>
                                ))}
                            </select>

                            {/* 排序方式 */}
                            <select
                                value={sortBy}
                                onChange={(e) => setSortBy(e.target.value as 'timestamp' | 'coinChange' | 'title')}
                                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
                            >
                                <option value="timestamp">按时间排序</option>
                                <option value="coinChange">按金币排序</option>
                                <option value="title">按标题排序</option>
                            </select>

                            {/* 排序顺序 */}
                            <select
                                value={sortOrder}
                                onChange={(e) => setSortOrder(e.target.value as 'asc' | 'desc')}
                                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
                            >
                                <option value="desc">降序</option>
                                <option value="asc">升序</option>
                            </select>
                        </motion.div>
                    )}
                </AnimatePresence>
            </Card>

            {/* 活动列表 */}
            {filteredActivities.length > 0 ? (
                <div className="grid gap-4">
                    <AnimatePresence mode="popLayout">
                        {filteredActivities.map((activity) => (
                            <ActivityCard key={activity.id} activity={activity}/>
                        ))}
                    </AnimatePresence>
                </div>
            ) : (
                <Card className="p-12 text-center">
                    <motion.div
                        initial={{opacity: 0, y: 20}}
                        animate={{opacity: 1, y: 0}}
                        className="space-y-4"
                    >
                        <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center">
                            <PhotoIcon className="w-8 h-8 text-gray-400"/>
                        </div>
                        <div>
                            <h3 className="text-lg font-medium text-gray-900">暂无记录</h3>
                            <p className="text-gray-500 mt-1">
                                {searchTerm || filterType !== 'all' || filterMood !== 'all'
                                    ? '没有匹配的记录，试试调整筛选条件'
                                    : '还没有任何活动记录，去添加一些吧！'
                                }
                            </p>
                        </div>
                    </motion.div>
                </Card>
            )}
        </div>
    );
};

export default EntryBoard;